<script setup lang="ts">
import { RouterView } from 'vue-router'
import { NMessageProvider, NConfigProvider, zhCN, dateZhCN } from 'naive-ui'
import NaiveUIProvider from '@/components/NaiveUIProvider/index.vue'
import { usePermissionStore } from '@/stores/permission'
import { useRouter } from 'vue-router'
import { getCurrentPermissionsApi } from '@/api/permission'
import type { PermissionItemType } from '@/types/api/permission'
import type { MenuOption } from 'naive-ui'

import { pathRouteMap } from '@/router/all_router'

const router = useRouter()
const { setPermission } = usePermissionStore()

// 获取当前用户权限
const getPermissions = async () => {
  const result = await getCurrentPermissionsApi()
  const permission = result.content
  traversePermission(permission)
  router.addRoute(pathRouteMap['/404'])
  setPermission(permission)
}

router.beforeEach((to, from, next) => {
  if (from.path === '/login') {
    getPermissions()
  }
  next()
})

if (location.pathname !== '/login') {
  getPermissions()
}

const traversePermission = (permissions: PermissionItemType[]): MenuOption[] => {
  const ret = permissions
    .filter(({ type }) => type === 'menu')
    .map((permission) => {
      const { id, path, permissionName, children } = permission
      // 动态添加路由
      if (path) {
        const route = pathRouteMap[path]
        if (route) {
          router.addRoute('home', pathRouteMap[path])
        } else {
          const placeholderRouteName = 'route-placeholer'
          router.addRoute('home', {
            path,
            name: `${placeholderRouteName}_${path}`,
            component: () => import('@/views/RoutePlaceholder/index.vue'),
            meta: {
              desc: permissionName
            }
          })
        }
      }
      return {
        label: permissionName,
        key: `${id}_${path}`,
        children: children.length ? traversePermission(children) : undefined
      }
    })
  return ret
}
</script>

<template>
  <NMessageProvider>
    <NConfigProvider :locale="zhCN" :date-locale="dateZhCN">
      <NaiveUIProvider>
        <RouterView></RouterView>
      </NaiveUIProvider>
    </NConfigProvider>
    <div id="__loader__"></div>
  </NMessageProvider>
</template>

<style>
#__loader__ {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 3;
  pointer-events: none;
  transition: all linear 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;

  &.loading {
    cursor: not-allowed;
    pointer-events: all;
    background-color: rgba(255, 255, 255, 0.5);
  }
}
</style>
